package com.thunder.soft.vm;

import android.util.Log;

import androidx.annotation.NonNull;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.MutableLiveData;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.thunder.soft.bean.ProjectBean;
import com.thunder.soft.common.base.BaseBean;
import com.thunder.soft.common.base.BaseViewModel;
import com.thunder.soft.common.net.HttpClient;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class ProjectViewModel extends BaseViewModel {

    int mPage = 0;
    private static final String TAG = ProjectViewModel.class.getName();
    private MutableLiveData<ProjectBean> projectLiveData = new MutableLiveData<>();

    @Override
    public void onCreate(@NonNull LifecycleOwner owner) {
        super.onCreate(owner);
        getProject();
    }

    public void getProject() {
        HttpClient.getInstance().request("project/list/" + mPage + "/json?cid=294", "GET", null, new Callback() {

            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                getErrorMsg().postValue(e.getMessage());
                Log.d(TAG, "error");
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                Gson gson = new Gson();
                String string = response.body().string();
                Log.e(TAG, string);

                BaseBean<ProjectBean> projectBean = gson.fromJson(string,
                        new TypeToken<BaseBean<ProjectBean>>() {
                        }.getType());

                if (projectBean.getErrorCode() == 0) { //success
                    projectLiveData.postValue(projectBean.getData());
                } else {
                    getErrorMsg().postValue(projectBean.getErrorMsg());
                }
            }
        });
    }

    public void refreshData(Boolean refresh) {
        if (refresh) {
            mPage = 0;
        } else {
            mPage++;
        }
        getProject();
    }

    public void onBackPressed() {
        getFinishActivity().postValue(1);
    }

    public MutableLiveData<ProjectBean> getProjectLiveData() {
        return projectLiveData;
    }
}